import { ProxyOptions, defineConfig, loadEnv } from 'vite';
import type { ConfigEnv } from 'vite';
import vue from '@vitejs/plugin-vue';

import { resolve } from 'path';

// 自动引入
import AutoImport from 'unplugin-auto-import/vite';

// 组件自动导入
import Components from 'unplugin-vue-components/vite';

// 本地mock
import { viteMockServe } from 'vite-plugin-mock';
import type { ViteMockOptions } from 'vite-plugin-mock';

const createViteServes = (env: Record<string, string>) => {
	const serveConfig: Record<string, string | ProxyOptions> = {
		host: '0.0.0.0',
		port: env.VITE_PORT,
	};

	if (env.VITE_APP_USE_MOCK === 'false') {
		console.log(env.VITE_APP_BASE_API);
		serveConfig.proxy = {
			[env.VITE_APP_BASE_API]: {
				target: 'http://localhost:3000',
				changeOrigin: true,
				// rewrite: (path: string) =>
				//   path.replace(`${env.VITE_APP_BASE_API}`, ``)
			},
		};
	}
	return serveConfig;
};

export default ({ mode }: ConfigEnv) => {
	const env = loadEnv(mode, process.cwd());

	return defineConfig({
		plugins: [
			vue(),
			AutoImport({
				//安装两行后你会发现在组件中不用再导入ref，reactive等
				imports: ['vue', 'vue-router'],
				//存放的位置
				dts: 'src/auto-import.d.ts',
			}),
			Components({
				// 引入组件的,包括自定义组件，存放的位置
				dts: 'src/components.d.ts',
			}),
			viteMockServe({
				mockPath: './mock/',
				supportTs: true, // 是否支持Ts文件模块
				logger: true, // 是否在控制台显示请求日志
				localEnabled: true, // 设置是否启用本地mock
				prodEnabled: true, // 设置打包是否启用mock
			} as ViteMockOptions),
		],
		resolve: {
			alias: {
				'@': resolve(__dirname, './src'),
				'~@': resolve(__dirname, './src'),
			},
		},
		server: createViteServes(env),
	});
};
